package net.neptech.config;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.neptech.config.properties.SecurityProperties;
import net.neptech.handler.AllUrlHandler;
import net.neptech.interceptor.HeaderInterceptor;
import net.neptech.utils.SpringUtils;
import net.neptech.vm.constant.SecurityConstants;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.DependsOn;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Arrays;

/**
 * @Author: liyuxiang
 * @Date: 2025/8/13 13:49
 * Security 权限安全配置
 */
@Slf4j
@AutoConfiguration
@DependsOn("securityProperties")
@EnableConfigurationProperties(SecurityProperties.class)
@RequiredArgsConstructor
public class SecurityConfig implements WebMvcConfigurer {

    private final SecurityProperties securityProperties;

    @PostConstruct
    public void init() {
        log.info("白名单路径加载: {}", Arrays.toString(securityProperties.getWhites().toArray()));
    }

    /**
     * 注册拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 1. 先注册HeaderInterceptor，用于设置用户上下文信息
        registry.addInterceptor(new HeaderInterceptor()).excludePathPatterns("/error");

        // 2. 注册Sa-Token拦截器，自定义验证规则
        registry.addInterceptor(new SaInterceptor(handler -> {
                    AllUrlHandler allUrlHandler = SpringUtils.getBean(AllUrlHandler.class);
                    // 检查是否为内部请求，如果是则跳过认证
                    String innerFlag = SaHolder.getRequest().getHeader(SecurityConstants.INNER);
                    if ("true".equals(innerFlag)) {
                        log.debug("检测到内部请求，跳过Sa-Token认证拦截");
                        return;
                    }

                    // 登录验证 -- 排除多个路径
                    SaRouter
                            // 获取所有的
                            .match(allUrlHandler.getUrls())
                            // 对未排除的路径进行检查
                            .check(() -> {
                                // 检查是否登录 是否有token
                                StpUtil.checkLogin();

                                // 有效率影响 用于临时测试
                                // if (log.isDebugEnabled()) {
                                //     log.debug("剩余有效时间: {}", StpUtil.getTokenTimeout());
                                //     log.debug("临时有效时间: {}", StpUtil.getTokenActivityTimeout());
                                // }

                            });
                })).addPathPatterns("/**")
                // 排除不需要拦截的路径
                .excludePathPatterns(securityProperties.getWhites()).excludePathPatterns("/error").order(0);
        ;
    }
}
